package com.audaque.springboot.foshanupload.jwt.component;

import cn.hutool.core.bean.BeanUtil;
import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import com.audaque.springboot.foshanupload.jwtcore.util.encode.rsaPem.RsaPem;
import com.audaque.springboot.foshanupload.jwtcore.util.encode.rsaPem.RsaUtil;
import com.audaque.springboot.foshanupload.jwtcore.component.iface.JwtProviderIface;
import com.audaque.springboot.foshanupload.jwtcore.properties.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author zgb
 * @desc ...
 * @date 2023-07-14 15:20:42
 */
@Component
@Slf4j
public class JwtTokenProvider {
    @Autowired
    private JwtProviderIface jwtProviderIface;

    @Autowired
    private JwtProperties jwtProperties;


    @Value("${db.tenantId}")
    private String tenantId;



    public void sendToken(HttpServletRequest request, HttpServletResponse response) throws Exception {

        TransmittableThreadLocalCurrentUser transmittableThreadLocalCurrentUser1 = TransmittableThreadLocalCurrentUser.getCurrentUser();
        if (transmittableThreadLocalCurrentUser1 != null) {
            //登录成功处理
            //发放令牌
            //jwt的负载要加密
            String id = transmittableThreadLocalCurrentUser1.getId();
            String username1 = transmittableThreadLocalCurrentUser1.getUsername();

            String secretKey = jwtProviderIface.generateKeyStr();
            String privateKey = jwtProperties.getPrivateKey();
            RsaUtil rsa = new RsaUtil(RsaPem.FromPEM(privateKey));
            String enId = rsa.Encode(id);
            String enUsername = rsa.Encode(username1);


            TransmittableThreadLocalCurrentUser transmittableThreadLocalCurrentUser = new TransmittableThreadLocalCurrentUser();
            transmittableThreadLocalCurrentUser.setId(enId);
            transmittableThreadLocalCurrentUser.setTenantId(tenantId);
            transmittableThreadLocalCurrentUser.setUsername(enUsername);

            Map<String, Object> map = BeanUtil.beanToMap(transmittableThreadLocalCurrentUser);
            map.put("verify", "verify");
            String accessToken = jwtProviderIface.getAccessToken(map);

            transmittableThreadLocalCurrentUser1.setAccessToken(accessToken);
            String accessTokenKey = jwtProperties.getAccessTokenKey();
            response.setHeader(accessTokenKey, accessToken);
        }
    }

}
